package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.TokenUtils;
import org.spring.kun.common.ZzyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class GiteeLoginController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/callbackCode.do")
    public String callback(String code, HttpServletResponse response) {
        System.out.println("接收到的临时授权码" + code);
        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token" + tokenByCode);

        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);
        System.out.println("获取到的用户信息" + JSON.toJSONString(userInfoByToken));

        //从20个字段  摘取 4个字段 进行注册
        String nickName = userInfoByToken.getString("name");// 把Name字段当做咱们系统的昵称
        String avatarUrl = userInfoByToken.getString("avatar_url");// 头像
        Integer giteeId = userInfoByToken.getInteger("id");//  把gitee的主键当做 giteeId字段
        String name = userInfoByToken.getString("login"); //把个人空间地址当做 数据库的用户名

        User userFromDB = userMapper.selectByName(name);
        if (userFromDB == null) {
            userFromDB = new User();
            userFromDB.setGiteeId(giteeId);
            userFromDB.setNickName(nickName);
            userFromDB.setName(name);
            userFromDB.setAvatarUrl(avatarUrl);
            userMapper.addUser(userFromDB);
        }

        // 加密用户信息 得到token  把token放入cookie  把cookie返回给浏览器
        TokenUtils.responseTokenByCookie(userFromDB, response);

        //发短信 用户在什么时间登录系统
        boolean flag = ZzyUtils.sendSms("17611221735", userFromDB.getName() + System.currentTimeMillis() + "登录了系统", 5);
        //把用户信息存入Redis 设置过期时间为30 min
        redisTemplate.opsForValue().set(userFromDB.getName(), JSON.toJSONString(userFromDB), 30, TimeUnit.MINUTES);
        return "redirect:list.do";
    }


}
